﻿let Emails_name = "";
let Emails_domain = "";
let Tables_obj = null;
let Enablesed = false;
appKey = "&*zfqn*&^3!wj_2bp0kq8%a#ml";

$(document).ready(function(){
	var loca = localStorage.getItem('TempMailNames');
	if(loca != null && loca.length > 0){
		Emails_name = loca;
		Enablesed = true;
	}
	var domain = localStorage.getItem('TempMailDomain');
	if(domain != null && domain.length > 0){
		Emails_domain = domain;
		Enablesed = true;
	}
	var clipboard = new ClipboardJS('#Copy_btn');
	clipboard.on('success', function(e) {
	    layer.msg('复制成功', {
			time: 2000,
	    });
	    e.clearSelection();
	});
	clipboard.on('error', function(e) {
		layer.msg('复制失败，请手动复制', {
			time: 2000,
		});
	});
	SetTable();
});

function SetTable(){
	GetUrl();
	var ts = new Date().getTime();
	layui.use('table', function(){
		var table = layui.table;
		Tables_obj = table;
		table.render({
			 elem: '#Table-ui'
			,url: '/api/email/select'
			,method: "POST"
			,toolbar: '#toolbar'
			,where: {
				name: Emails_name,
				timestamp: ts,
				domain: Emails_domain,
				sign: Sign(Emails_name, ts.toString())
			}
			,text: {
				none: '暂无邮件'
			}
			,defaultToolbar: []
			,cols: [[
			     {field: 'Uid', hide: true}
			    ,{field: 'Title', width: 250, minWidth: 250, style: 'cursor: pointer;', title: '邮件标题', event: "title"}
				,{field: 'From', width: 200, minWidth: 200, style: 'cursor: pointer;', title: '发件人', event: "from"}
				,{field: 'Value', width: 400, minWidth: 400, style: 'cursor: pointer;', title: '邮件内容', event: "value"}
				,{fixed: 'right', toolbar: '#barBtn', width:66}
			]],
			done: function(res, curr, count){
			    if(Enablesed){
					Enabled();
				}
				else{
					Disabled();
				}
				$('#Mail-Name').bind("keydown", function (e) {
				    var theEvent = e || window.event;
				    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
				    if (code === 13) {
				        GetMail($('#Mail-Name').val(), $("dd[class='layui-this']").html());
				    }
				});
			}
		});

		//监听行工具事件
        table.on('tool(Table-ui)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.open({
				    content: '删除后无法恢复！是否继续？'
				    ,shadeClose: false
				    ,btn: ['确定', '取消']
				    ,skin: 'demo-class'
				    ,yes: function(index, layero){
				        Remail(data.Uid, Emails_name, Emails_domain);
				        parent.layer.close(index);
				    }
				    ,btn2: function(index, layero){
					    return true;
				    }
				    ,cancel: function(){
				        return true;
				    }
			    });
            }else if(obj.event === 'value'){
                layer.alert(data.Value, {
                    title: "邮件内容",
                    shadeClose: true,
                    area: 'auto',
                    maxWidth: 800,
                    maxHeight: 700,
                    skin: 'demo-class'
			    });
            }else if(obj.event === 'title'){
                layer.alert(data.Title, {
                    title: "邮件标题",
                    shadeClose: true,
                    area: 'auto',
                    maxWidth: 800,
                    maxHeight: 700,
                    skin: 'demo-class'
			    });
            }else if(obj.event === 'from'){
                layer.alert(data.From, {
                    title: "发件人",
                    shadeClose: true,
                    area: 'auto',
                    maxWidth: 800,
                    maxHeight: 700,
                    skin: 'demo-class'
			    });
            }
        });
		table.on('toolbar(Table-ui)', function(obj){
			emails = $('#Mail-Name').val();
			domain = $("dd[class='layui-this']").html();
		    switch(obj.event){
				case 'GetEmail':
					if(Enablesed === false){
						GetMail(emails, domain);
					}
					else{
						SetTable();
					}
					break;
				case 'DelEmail':
					if(Enablesed === true){
						layer.open({
							content: '注销邮箱可能会导致后期无法找回，是否继续？'
							,shadeClose: false
							,btn: ['确定', '取消']
							,skin: 'demo-class'
							,yes: function(index, layero){
								//DelMail(emails, domain);
								Emails_name = "";
								Emails_domain = "";
								Enablesed = false;
								localStorage.removeItem("TempMailNames");
								localStorage.removeItem('TempMailDomain');
								SetTable();
								parent.layer.close(index);
							}
							,btn2: function(index, layero){
								return true;
							}
							,cancel: function(){
								return true;
							}
						});
					}
					else{
						SetTable();
					}
					break;
				case 'SelEmail':
					SetTable();
					break;
		    }
		});
	});

}

function GetMail(name, domain){
	var ts = new Date().getTime();
	$.ajax({
	    type: "POST",
	    url : "/api/email/create",
	    data: {
			"name": name,
			"domain": domain,
			"timestamp": ts,
			"sign": Sign(name, ts.toString())
		},
	    success:function(data){
			var msg = data.msg;
			if(msg === "success" || msg === "Success" || msg === "该账号已存在"){
				Emails_name = name;
				Emails_domain = domain;
				Enablesed = true;
				localStorage.setItem('TempMailNames', name);
				localStorage.setItem('TempMailDomain', domain);
				SetTable();
			}
			else{
				layer.alert(data.msg, {
					title: '返回信息',
					shadeClose: true,
					skin: 'demo-class'
				});
			}
		},
	    error:function(ex){
	        layer.alert(ex.responseText, {
	        	title: '错误',
	        	shadeClose: true,
				skin: 'demo-class'
	        });
	    }
	});
}

function DelMail(name, domain){
	var ts = new Date().getTime();
	$.ajax({
	    type: "POST",
	    url : "/api/email/delete",
	    data: {
			"name": name,
			"domain": domain,
			"timestamp": ts,
			"sign": Sign(name, ts.toString())
		},
	    success:function(data){
			var msg = data.msg;
			if(msg === "success" || msg === "Success" || msg === "该账号不存在"){
				Emails_name = "";
				Emails_domain = "";
				Enablesed = false;
				localStorage.removeItem("TempMailNames");
				localStorage.removeItem('TempMailDomain');
				SetTable();
			}
			else{
				layer.alert(data.msg, {
					title: '返回信息',
					shadeClose: true,
					skin: 'demo-class'
				});
			}
		},
	    error:function(ex){
	        layer.alert(ex.responseText, {
	        	title: '错误',
	        	shadeClose: true,
				skin: 'demo-class'
	        });
	    }
	});
}

function GetUrl(){
	var ts = new Date().getTime();
	$.ajax({
	    type: "POST",
	    url : "/api/email/geturl",
	    data: {
			"name": "geturl",
			"timestamp": ts,
			"sign": Sign("geturl", ts.toString())
		},
	    success:function(data){
			var msg = data.msg;
			var msglist = msg.split(',');

			if(msglist[0] === "Success"){
				$('#Select_Mail').html('');
				for(var i = 1; i < msglist.length; i++){
					$('#Select_Mail').html($('#Select_Mail').html() + '<option value="@' + msglist[i] + '">@' + msglist[i] + '</option>');
				}
				if(Enablesed){
					Enabled();
				}
				else{
					Disabled();
				}
			}
			else{
				layer.alert(msg, {
					title: '返回信息',
					shadeClose: true,
					skin: 'demo-class'
				});
			}
		},
	    error:function(ex){
	        layer.alert(ex.responseText, {
	        	title: '错误',
	        	shadeClose: true,
				skin: 'demo-class'
	        });
	    }
	});
}

function Remail(uid, name, domain){
	var ts = new Date().getTime();
	$.ajax({
	    type: "POST",
	    url : "/api/email/remail",
	    data: {
	    	"uid": uid,
			"name": name,
			"domain": domain,
			"timestamp": ts,
			"sign": Sign(name, ts.toString())
		},
	    success:function(data){
			var msg = data.msg;
			if(msg === "Success"){
				SetTable();
			}
			else{
				layer.alert(msg, {
					title: '返回信息',
					shadeClose: true,
					skin: 'demo-class'
				});
			}
		},
	    error:function(ex){
	        layer.alert(ex.responseText, {
	        	title: '错误',
	        	shadeClose: true,
				skin: 'demo-class'
	        });
	    }
	});
}

function Sign(name, stamp){
	var strName = appKey + '{"name":"' + name + '","timestamp":' + stamp + ',"appkey":"' + appKey + '"}' + appKey;
	var md5str = hex_md5(strName);
	return md5str
}

function Enabled(){
	layui.use('form', function(){
	    var form = layui.form;

		$("#Sel-Email").attr("disabled", false);
		$("#Del-Email").attr("disabled", false);
		$("#Sel-Email").removeClass("layui-btn-disabled");
		$("#Del-Email").removeClass("layui-btn-disabled");
		$("#Get-Email").addClass("layui-btn-disabled");
		$("#Mail-Name").addClass("layui-disabled");
		$("#Mail-Name").attr("disabled", true);
		$("#Get-Email").attr("disabled", true);
		$("#Mail-Name").val(Emails_name);
		$('#Copy_btn').attr("data-clipboard-text", Emails_name + Emails_domain);
		$('#EmailText').html("当前临时邮箱： " + Emails_name + Emails_domain);
		$("#EmailValue").removeAttr("style","");
		$('#Select_Mail').attr("disabled", true);
		$('#Select_Mail').addClass('layui-select-disabled');
		$('select').val(Emails_domain);

	    form.render('select');
	});
}

function Disabled(){
	layui.use('form', function(){
	    var form = layui.form;

		$("#Sel-Email").attr("disabled", true);
		$("#Del-Email").attr("disabled", true);
		$("#Sel-Email").addClass("layui-btn-disabled");
		$("#Del-Email").addClass("layui-btn-disabled");
		$("#Get-Email").removeClass("layui-btn-disabled");
		$("#Mail-Name").removeClass("layui-disabled");
		$("#Mail-Name").attr("disabled", false);
		$("#Get-Email").attr("disabled", false);
		$('#EmailValue').val("");
		$("#EmailValue").attr("style", "display: none;");
		$('#Select_Mail').attr("disabled", false);
		$("#Select_Mail").removeClass("layui-select-disabled");

	    form.render('select');
	});
}